package com.truyentranh.main;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.SessionStore;
import com.facebook.android.Utility;
import com.truyentranh.R;
import com.truyentranh.controls.AdsViewControl;
import com.truyentranh.data.HaiBLModule;
import com.truyentranh.data.TipData;
import com.truyentranh.modules.cabvn.CabVnActivity;
import com.truyentranh.modules.girl.GirlActivity;
import com.truyentranh.modules.haivl.HaiVLActivity;
import com.truyentranh.modules.local.MoreActivity;
import com.truyentranh.modules.news.NewsActivity;
import com.truyentranh.modules.ohvui.OhVuiActivity;
import com.truyentranh.modules.tamdiem.TamDiemActivity;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.UpdateRequester;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.Logger;
import com.truyentranh.utils.sqllite.datasource.TopicHaiBlData;

public class HaiBLActivity extends Activity implements OnItemClickListener {
	ListView mainContentList;
	public static final String APP_ID = "354042864672977";// "157111564357680";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Logger.logMe("onCreateonCreateonCreateonCreate");
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.haibl_activity_main);
		mainContentList = (ListView) findViewById(R.id.mainContentList);

		ArrayList<HaiBLModule> modules = getModules();

		HaiBLModulesRenderAdapter haiBLModulesRenderAdapter = new HaiBLModulesRenderAdapter(getApplicationContext(), 1, 1, modules);
		mainContentList.setAdapter(haiBLModulesRenderAdapter);
		mainContentList.setSelected(false);
		mainContentList.setOnItemClickListener(this);
		int[] colors = { 0, 0xFF000000, 0 };
		mainContentList.setDivider(new GradientDrawable(Orientation.LEFT_RIGHT, colors));
		mainContentList.setDividerHeight(1);

		AppSettingParams.SCREEN_WIDTH = getWindowManager().getDefaultDisplay().getWidth();
		AppSettingParams.SCREEN_HEIGHT = getWindowManager().getDefaultDisplay().getHeight();

		// Create the Facebook Object using the app id.
		Utility.mFacebook = new Facebook(APP_ID);
		// Instantiate the asynrunner object for asynchronous api calls.
		Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

		SessionStore.restore(Utility.mFacebook, this);
	}

	protected void onStart() {

		// try {
		// PackageInfo info = getPackageManager().getPackageInfo("com.haibl",
		// PackageManager.GET_SIGNATURES);
		// for (Signature signature : info.signatures) {
		// MessageDigest md = MessageDigest.getInstance("SHA");
		// md.update(signature.toByteArray());
		// DisplayUtils.openNoticeDialog("test",
		// Base64.encodeBytes(md.digest()), this, null);
		// Log.i("PXR", Base64.encodeBytes(md.digest()));
		// }
		// }
		// catch (NameNotFoundException e) {}
		// catch (NoSuchAlgorithmException e) {}
		Logger.logMe("onStartonStartonStartonStartonStartonStart");
		if (!AdsViewControl.NO_ADS) {
			AppSettingParams.initPublishId(HaiBLActivity.this);
			doCallUpdatesVersion();
		}
		AppSettingParams.initSession(this);
		AppSettingParams.initFaceBookAppId(HaiBLActivity.this);

		mainContentList.setSelected(false);
		TopicHaiBlData blData = ComicSessionStore.restoreDefaultTopic(this);
		if (blData != null && blData.getId() != -1) {
			boolean isExists = ComicBussiness.getInstance(this).isDefaultTopicHasExists(blData.getId());
			if (isExists) {
				ComicBussiness.getInstance(this).setDefaultComicTopic(new TopicHaiBlData(blData.getId(), blData.getName()));
			}
		}
		super.onStart();
	};

	ArrayList<HaiBLModule> modules;

	private ArrayList<HaiBLModule> getModules() {
		if (modules == null) {
			modules = new ArrayList<HaiBLModule>();
			modules.add(new HaiBLModule("Hài vui lắm", "", HaiBLModule.HAIVL));			
//			modules.add(new HaiBLModule("Quầy báo", "", HaiBLModule.QUAYBAO));
			modules.add(new HaiBLModule("Oh vui quá", "", HaiBLModule.OHVUI));
			modules.add(new HaiBLModule("ME-chia sẻ ni�?m vui", "", HaiBLModule.CABVN));
			modules.add(new HaiBLModule("Girl xinh vô đối", "", HaiBLModule.GIRLXINH));
			modules.add(new HaiBLModule("Kho ảnh", "", HaiBLModule.TAMDIEM));
			modules.add(new HaiBLModule("Nhi�?u hơn nữa...", "", ""));
			
		}
		return modules;
	}

	public void onClick(View v) {

	}

	public static boolean isCall = false;

	void doCallUpdatesVersion() {
		if(isCall) return;
		isCall = true;
		UpdateRequester updateRequester = new UpdateRequester(new RequestListener() {

			public void onRequestFailed(String errorMsg, Request request) {

			}

			public void onRequestComplete(Request request) {
				if (request instanceof UpdateRequester) {
					final UpdateRequester r = (UpdateRequester) request;
					if (r.getVersion() > AppSettingParams.VERSION_CODE) {
						final String message = r.getMessage();
						final String title = "Cập nhật" + (r.isForce() ? " bắt buộc" : "");
						final String link = r.getLink();
						// has new updates for app

						final AlertDialog.Builder alert = DisplayUtils.showUpdatesDialog(r.isForce(), title, message, HaiBLActivity.this, new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								finish();

								Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
								startActivity(browserIntent);
							}
						}, new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								if (r.isForce()) {
									finish();
								}
							}
						}, null);

						runOnUiThread(new Runnable() {
							public void run() {
								try {
									alert.show();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						});
					} else {
						System.out.println("show tip");
						// show tip len
						final TipData data = r.getTipdata();
						if (data != null) {
							System.out.println("show tip");
							runOnUiThread(new Runnable() {
								public void run() {
									DisplayUtils.openTipDialog("Chú ý", data.getMesage(), data.getLink(), HaiBLActivity.this);
								}
							});

						}
					}
				}

			}
		});

		APIRequestWorker.getInstance().addAPIRequest(updateRequester);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		final ArrayList<HaiBLModule> modules = getModules();
		if (modules != null) {
			HaiBLModule module = modules.get(index);
			final String id = module.getId();
			if (HaiBLModule.HAIVL.equals(id)) {
				Intent intent = new Intent(getApplication(), HaiVLActivity.class);
				startActivity(intent);
			} else if (HaiBLModule.CABVN.equals(id)) {
				Intent intent = new Intent(getApplication(), CabVnActivity.class);
				startActivity(intent);
			} else if (HaiBLModule.OHVUI.equals(id)) {
				Intent intent = new Intent(getApplication(), OhVuiActivity.class);
				startActivity(intent);
			} else if (HaiBLModule.TAMDIEM.equals(id)) {
				Intent intent = new Intent(getApplication(), TamDiemActivity.class);
				startActivity(intent);
			}  else if (HaiBLModule.QUAYBAO.equals(id)) {
				Intent intent = new Intent(getApplication(), NewsActivity.class);
				startActivity(intent);
			} else if (HaiBLModule.GIRLXINH.equals(id)) {
				Intent intent = new Intent(getApplication(), GirlActivity.class);
				startActivity(intent);
			} else {
				Intent intent = new Intent(getApplication(), MoreActivity.class);
				startActivity(intent);
			}
		}
	}

}
